<template>
 <Fade>
    <div v-show="this.$store.state.data">
      <div class="header">
        <img src="@/assets/error.png"
            alt=""
            @click="goHome">
        <div class="title">当前城市</div>
      </div>
      <van-search v-model="value"
                  placeholder="请输入城市名或拼音"
                  @search="onSearch(value)" />
      <div class="content"
          v-if="keyword.length==0">
        <div class="label">GPS定位你所在的城市</div>
        <van-button>{{city}}</van-button>
        <div class="label">热门城市</div>
        <van-button v-for="item of result.hotCities"
                    :key="item.id"
                    @click="handleChange(item.name)">{{item.name}}</van-button>
        <van-index-bar :index-list="indexList">
          <div v-for="(item,index) in result.cities"
              :key="index">
            <van-index-anchor :index="index">{{index}}</van-index-anchor>
            <van-cell :title="value.name"
                      v-for="value of item"
                      :key="value.id"
                      @click="handleChange(value.name)" />
          </div>
        </van-index-bar>
      </div>

      <div v-if="keyword.length!=0">
        <van-cell :title="item.name"
                  v-for="item of searchCities"
                  :key="item.id"
                  @click="handleChange(item.name)" />
      </div>
    </div>
 </Fade>
</template>

<script>
import Fade from '../components/Fade.vue'
export default {
  components: { Fade },
  name: 'City',
  data () {
    return {
      value: '',
      indexList: [],
      result: '',
      city: "",
      keyword: "",
      searchCities: []
    }
  },
  mounted () {
    this.city = localStorage.getItem('city')
    this.$http.get('http://47.108.197.28:8000/city').then(res => {
      this.result = res.data.data
      this.indexList = Object.keys(this.result.cities)
    })
  },
  methods: {
    goHome () {
      this.$router.push('/tab/films/nowPlaying')
    },
    handleChange (name) {
      localStorage.setItem('city', name)
      this.$router.push({ path: '/tab/films/nowPlaying' })
    },
    onSearch (value) {
      this.keyword = value
      var cities = this.result.cities
      for (let key in cities) {
        cities[key].forEach(item => {
          if (item.name.includes(value) || item.spell.includes(value)) {
            this.searchCities.push(item)
          }
        })
      }
    }
  }
}
</script>

<style scoped>
.header {
  padding: 2vw;
  display: flex;
}
.header img {
  width: 8vw;
  height: 8vw;
}
.title {
  width: 80%;
  line-height: 8vw;
  font-size: 5.5vw;
  text-align: center;
}
.content {
  padding: 4vw;
}
.content .label {
  font-size: 4vw;
  color: #666;
  margin-bottom: 2vw;
}
.van-button {
  background-color: #eee;
  height: 10vw;
  margin-bottom: 2vw;
  margin-right: 2vw;
}
</style>